<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/10/29 0029
 * Time: 16:11
 */

namespace app\index\controller;
use app\index\model\User;
use PHPMailer\Mail;
use think\Controller;
use think\Loader;
require_once("../vendor/qqConnect/API/qqConnectAPI.php");

class Login extends Controller
{
	/**
	 * 登陆页面主页
	 * @return mixed
	 */
	public function index(){
		$this->assign('title', '登陆');
		return $this->fetch();
	}


	/**
	 * 检测登陆，是否有该用户
	 */
	public function checkLogin(){
		$post = input('post.');
		$validate = Loader::validate('CheckReg');
		if(!$validate->scene('captcha')->check($post)){
			$this->error($validate->getError());
		}
		if (strpos($post['phone'],'@')){
			$res = User::where(['email'=>$post['phone'],'password'=>md5($post['password'])])->find();
			if ($res){
				session('user_id',$res->user_id);
				session('nickname',$res->nickname);
				session('face',$res->face);
				$this->success('登陆成功');
			}else{
				$this->error('账号密码错误');
			}
		}else{
			$res = User::where(['phone'=>$post['phone'],'password'=>md5($post['password'])])->find();
			if ($res){
				session('user_id',$res->user_id);
				session('nickname',$res->nickname);
				session('face',$res->face);
				$this->success('登陆成功');
			}else{
				$this->error('账号密码错误');
			}
		}
	}


	/**
	 * 退出登陆
	 */
	public function loginOut(){
		session(null);
		header("Location:".url('index/login/index'));
	}


	/**
	 * 忘记密码主页
	 * @return mixed
	 */
	public function forgetPass(){
	    return $this->fetch();
	}


	/**
	 * 修改密码方法
	 */
	public function forgetPassword(){
		$post = input('post.');
		$validate = Loader::validate('CheckReg');
		if(!$validate->scene('captcha')->check($post)){
			$this->error($validate->getError());
		}
		$user = User::get(['email'=>$post['email']]);
		$nickname = $user->nickname;
		if (!$user){
			$this->error('对不起,没有找到该用户');
		}
		$token = md5(date('Ymd His').mt_rand(0,999999));
		$url = 'http://www.flyx.com'.url('index/Login/resetPass').'?email='.$user->email.'&token='.$token;
		$content = <<<xx
		<div><br></div><div><includetail><table border="0" cellpadding="0" cellspacing="0" style="width: 600px; border: 1px solid #ddd; border-radius: 3px; color: #555; font-family: 'Helvetica Neue Regular',Helvetica,Arial,Tahoma,'Microsoft YaHei','San Francisco','微软雅黑','Hiragino Sans GB',STHeitiSC-Light; font-size: 12px; height: auto; margin: auto; overflow: hidden; text-align: left; word-break: break-all; word-wrap: break-word;"> <tbody style="margin: 0; padding: 0;"> <tr style="background-color: #393D49; height: 60px; margin: 0; padding: 0;"> <td style="margin: 0; padding: 0;"> <div style="color: #5EB576; margin: 0; margin-left: 30px; padding: 0;"><a style="font-size: 14px; margin: 0; padding: 0; color: #5EB576; text-decoration: none;" href="http://fly.layui.com/" target="_blank">Fly社区 - Layui前端框架官方社区</a></div> </td> </tr> <tr style="margin: 0; padding: 0;"> <td style="margin: 0; padding: 30px;"> <p style="line-height: 20px; margin: 0; margin-bottom: 10px; padding: 0;"> 你好，<em style="font-weight: 700;">{$nickname}</em>童鞋，请在30分钟内重置您的密码： </p> <div style=""> <a href={$url} style="background-color: #009E94; color: #fff; display: inline-block; height: 32px; line-height: 32px; margin: 0 15px 0 0; padding: 0 15px; text-decoration: none;" target="_blank">立即重置密码</a> </div> <p style="line-height: 20px; margin-top: 20px; padding: 10px; background-color: #f2f2f2; font-size: 12px;"> 如果该邮件不是由你本人操作，请勿进行激活！否则你的邮箱将会被他人绑定。 </p> </td> </tr> <tr style="background-color: #fafafa; color: #999; height: 35px; margin: 0; padding: 0; text-align: center;"> <td style="margin: 0; padding: 0;">系统邮件，请勿直接回复。</td> </tr> </tbody> </table></includetail></div>
xx;
		$res = Mail::sendMail($post['email'],'Fly社区找回密码',$content);
		if (!$res){
			$this->error('发送失败');
		}else{
			session('token',$token);
			session('email',$user->email);
			session('create_time',time());
			$this->success('邮件已发送,请注意查看');
		}
	}


	/**
	 * 重置密码主页
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
	public function resetpass(){
		$user = User::get(['email'=>input('email')]);
		if (!$user){
			$this->error('出现错误，请重新尝试');
		}
		var_dump(session(''));
		$this->assign('user',$user);
		return $this->fetch();
	}


	/**
	 * 重置密码方法
	 * @throws \think\exception\DbException
	 */
	public function resetPassword(){
		$post = input('post.');
		$validate = Loader::validate('CheckReg');
		if(!$validate->scene('cp')->check($post)){
			$this->error($validate->getError());
		}
		$user = User::get(['nickname'=>$post['nickname'],'email'=>$post['email']]);
		if ($user){
			$res = User::where(['nickname'=>$post['nickname'],'email'=>$post['email']])->update(['password'=>md5($post['password'])]);
			if ($res){
				$this->success('更改成功');
			}else{
				$this->error('更改失败,请稍后再试');
			}
		}else{
			$this->error('对不起,没有找到该用户');
		}
	}


	/**
	 * qq登陆
	 */
	public function qqLogin(){
		$qc = new \QC();
		$qc->qq_login();
	}


	/**
	 * qq回调方法
	 * @throws \think\exception\DbException
	 */
	public function qqReturn(){
		$qc = new \QC();
		$qc->qq_callback();
		$openid = $qc->get_openid();
		$user = User::get(['openid'=>$openid]);
		if ($user){
			session('user_id',$user->user_id);
			session('nickname',$user->nickname);
			session('face',$user->face);
			header('location:'.url('index/UserCenter/index'));
		}else{
			$qc = new \QC();
			$userInfo = $qc->get_user_info();
			$data['nickname'] = $userInfo['nickname'];
			$data['sex'] = $userInfo['gender']=='男' ? 0 : 1;
			$data['city'] = $userInfo['province'].'-'.$userInfo['city'];
			$data['openid'] = $openid;
			$data['create_time'] = time();
			$data['face'] = $this->getFace($userInfo['figureurl_qq_2']);
			$res = User::create($data);
			if ($res){
				session('user_id',$res->user_id);
				session('nickname',$res->nickname);
				session('face',$res->face);
				header('location:'.url('index/UserCenter/index'));
			}else{
				$this->error('出现错误,请稍后再试');
			}
		}
	}


	public function getFace($url=''){
		// 1. 初始化
		$ch = curl_init();
		// 2. 设置选项，包括URL
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_HEADER,0);
		$output = curl_exec($ch);
		curl_close($ch);
		$dir = './static/uploads/';
		$dirs = $dir.date('Ymd');
		is_dir($dir) || mkdir($dir);
		is_dir($dirs) || mkdir($dirs);
		$face = $dirs.'/'.uniqid().'.jpg';
		file_put_contents($face,$output);
		return $face;
	}
}